package com.example.javaproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.javaproject.entity.Position;
import com.example.javaproject.mapper.PositionMapper;
import com.example.javaproject.service.PositionService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import com.example.javaproject.dto.TeacherStatsDTO;
import com.example.javaproject.entity.PositionApplication;
import com.example.javaproject.entity.Salary;
import com.example.javaproject.mapper.PositionApplicationMapper;
import com.example.javaproject.mapper.SalaryMapper;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class PositionServiceImpl extends ServiceImpl<PositionMapper, Position> implements PositionService {
    @Autowired
    private PositionApplicationMapper positionApplicationMapper;

    @Autowired
    private SalaryMapper salaryMapper;

    @Override
    public boolean add(Position position) {
        return save(position);
    }

    @Override
    public boolean deleteById(Integer id) {
        Position position = getById(id);
        if (position == null) return false;
        position.setIsDeleted(1);
        position.setUpdateTime(new java.util.Date());
        return updateById(position);
    }

    @Override
    public boolean updatePosition(Position position) {
        return updateById(position);
    }

    @Override
    public List<Map<String, Object>> getPositionStats() {
        return baseMapper.selectMaps(new QueryWrapper<Position>()
            .select("name as name, count(*) as value")
            .eq("is_deleted", 0)
            .groupBy("name")
            .orderBy(true, false, "value"));
    }

    @Override
    public List<Map<String, Object>> getApplicationStats() {
        return baseMapper.selectApplicationStats();
    }

    @Override
    public Map<String, Object> getPositionWithTeacher(Integer id) {
        return baseMapper.selectPositionWithTeacher(id);
    }

    @Override
    public List<Map<String, Object>> getAllPositionsWithTeacher() {
        return baseMapper.selectAllPositionsWithTeacher();
    }

    @Override
    public TeacherStatsDTO getTeacherStats(Integer teacherId) {
        TeacherStatsDTO stats = new TeacherStatsDTO();
        
        // 获取教师发布的所有岗位
        QueryWrapper<Position> positionQuery = new QueryWrapper<>();
        positionQuery.eq("teacher_id", teacherId)
                     .eq("is_deleted", 0);
        List<Position> positions = baseMapper.selectList(positionQuery);
        
        stats.setTotalPositions(positions.size());
        
        List<TeacherStatsDTO.PositionStatsDetail> positionDetails = new ArrayList<>();
        int totalApplications = 0;
        BigDecimal totalSalaryPaid = BigDecimal.ZERO;
        BigDecimal totalSalary = BigDecimal.ZERO;
        
        for (Position position : positions) {
            TeacherStatsDTO.PositionStatsDetail detail = new TeacherStatsDTO.PositionStatsDetail();
            detail.setPositionId(position.getId());
            detail.setPositionName(position.getName());
            
            // 获取岗位申请数量
            QueryWrapper<PositionApplication> appQuery = new QueryWrapper<>();
            appQuery.eq("position_id", position.getId())
                    .eq("is_deleted", false);
            List<PositionApplication> applications = positionApplicationMapper.selectList(appQuery);
            detail.setApplicationCount(applications.size());
            totalApplications += applications.size();
            
            // 获取已录用数量（状态为已通过的申请）
            QueryWrapper<PositionApplication> approvedQuery = new QueryWrapper<>();
            approvedQuery.eq("position_id", position.getId())
                         .eq("status", 1) // 假设1表示已通过
                         .eq("is_deleted", false);
            List<PositionApplication> approvedApps = positionApplicationMapper.selectList(approvedQuery);
            detail.setApprovedCount(approvedApps.size());
            
            // 获取工资信息
            QueryWrapper<Salary> salaryQuery = new QueryWrapper<>();
            salaryQuery.eq("position_id", position.getId())
                       .eq("is_deleted", false);
            List<Salary> salaries = salaryMapper.selectList(salaryQuery);
            
            BigDecimal positionTotalSalary = BigDecimal.ZERO;
            BigDecimal positionPaidSalary = BigDecimal.ZERO;
            
            for (Salary salary : salaries) {
                positionTotalSalary = positionTotalSalary.add(salary.getTotalSalary());
                if (salary.getStatus() == 1) { // 假设1表示已发放
                    positionPaidSalary = positionPaidSalary.add(salary.getTotalSalary());
                }
            }
            
            detail.setTotalSalary(positionTotalSalary);
            detail.setPaidSalary(positionPaidSalary);
            totalSalary = totalSalary.add(positionTotalSalary);
            totalSalaryPaid = totalSalaryPaid.add(positionPaidSalary);
            
            // 计算发放率
            if (positionTotalSalary.compareTo(BigDecimal.ZERO) > 0) {
                double rate = positionPaidSalary.divide(positionTotalSalary, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100")).doubleValue();
                detail.setPaymentRate(String.format("%.1f", rate));
            } else {
                detail.setPaymentRate("0.0");
            }
            
            // 设置岗位状态
            detail.setStatus(getPositionStatusText(position.getStatus()));
            
            positionDetails.add(detail);
        }
        
        stats.setTotalApplications(totalApplications);
        stats.setTotalSalaryPaid(totalSalaryPaid);
        stats.setPositionDetails(positionDetails);
        
        // 计算总体工资发放率
        if (totalSalary.compareTo(BigDecimal.ZERO) > 0) {
            double totalRate = totalSalaryPaid.divide(totalSalary, 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100")).doubleValue();
            stats.setSalaryPaymentRate(String.format("%.1f%%", totalRate));
        } else {
            stats.setSalaryPaymentRate("0.0%");
        }
        
        return stats;
    }

    private String getPositionStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 1: return "招聘中"; // 招聘中
            case 2: return "暂停"; // 暂停
            case 3: return "已结束"; // 已结束
            default: return "未知";
        }
    }

    @Override
    public Position getActiveById(Integer id) {
        return this.lambdaQuery().eq(Position::getId, id).eq(Position::getIsDeleted, 0).one();
    }

    @Override
    public Map<String, Object> getTeacherPositions(Map<String, Object> params) {
        return this.baseMapper.selectTeacherPositions(params);
    }
}